<?php

namespace App\Http\Controllers\Api;

use App\Models\Activity;
use App\Models\Advert;
use App\Models\Area;
use App\Models\Article;
use App\Models\ArticleClass;
use App\Models\Config;
use App\Models\Dict;
use App\Models\House;
use App\Models\Icons;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\Exceptions\Exception;

class ToolsController extends Controller
{

    //网站配置
    public function getConfig(Request $request)
    {
        $id = $request->get('id');
        $config = Config::where(['id' => $id])->first();
        if ($config['privacy']) {
            $config['privacy'] = replaceOssImgSrc($config['privacy']);
        }
        if ($config['site_open']) {
            $config['site_open'] = getAliOssImage($config['site_open']);
        }
        return showMsg('获取成功', 200, $config);
    }

    //网站配置
    public function getDict(Request $request)
    {
        $array = [];
        $dictname = $request->get('dictname');
        foreach ($dictname as $value) {
            $array[$value] = Dict::select('id', 'dkey', 'dvalue', 'dicon')->where(['dictname' => $value, 'status' => 1])->where('did', '!=', 0)->orderBy('sort', 'asc')->get();
        }
        //$config = Dict::select('id', 'dkey', 'dvalue')->where(['dictname' => $dictname])->where('status', 1)->orderBy('sort', 'asc')->get();
        return showMsg('获取成功', 200, $array);
    }

    //获取区域
    public function getArea(Request $request)
    {
        $keys = $request->get('keys');
        $model = Area::query();
        $model = $model->with('children');
        if ($keys) {
            $model = $model->where('title', 'like', '%' . $keys . '%');
        }
        $model = $model->where('par_id', 0);
        $model = $model->orderBy('sort', 'asc');
        $result = $model->get();
        return showMsg('操作成功', 200, $result);
    }

    //获取城市
    public function getLocation(Request $request)
    {
        $keys = $request->get('keys');
        $model = Area::query();
        if ($keys) {
            $model = $model->where('title', 'like', '%' . $keys . '%');
        }
        $result = $model->first();
        if (empty($result)) {
            $result = Area::where('id', 1)->first();
        }
        return showMsg('操作成功', 200, $result);
    }

    //新版首页
    public function getIndex(Request $request)
    {
        $city_id = $request->get('city_id');
        //轮播图
        $advert = Advert::select('id', 'title', 'thumb', 'urls', 'urls_type')->where('type', 0)->where('status', 1)->orderBy('sort', 'asc')->get();
        foreach ($advert as $value) {
            if ($value['thumb']) {
                $value['thumb'] = getAliOssImage($value['thumb']);
            }
        }
        $array['advert'] = $advert;

        //快讯
        $quick = Article::select('id', 'class_id', 'title', 'urls')->where('class_id', 1)->orderBy('id', 'desc')->first();
        $array['quick'] = $quick;

        $map = Advert::select('id', 'title', 'thumb', 'urls')->where('type', 1)->where('status', 1)->orderBy('id', 'desc')->first();
        if ($map['thumb']) {
            $map['thumb'] = getAliOssImage($map['thumb']);
        }
        $array['map'] = $map;

        //好房
        $model = House::query();
        $model = $model->select('id', 'title', 'province_id', 'city_id', 'status', 'price', 'address', 'house', 'imgs', 'tags', 'drawing', 'project');
//        if ($city_id) {
//            $model = $model->where('city_id', $city_id);
//        }
        $house = $model->where('status', 1)->orderBy('sort', 'asc')->orderBy('id', 'desc')->get();
        foreach ($house as $value) {
            if ($value['drawing']) {
                $value['drawing'] = getAliOssImage($value['drawing']);
            }
            if ($value['project']) {
                $value['project'] = getAliOssImage($value['project']);
            }
            if ($value['tags']) {
                $value['tags'] = explode(',', $value['tags']);
            }
        }
        $array['house'] = $house;

        //好房
        $models = House::query();
        $models = $models->select('id', 'title', 'province_id', 'city_id', 'status', 'house', 'imgs', 'price', 'drawing', 'project');
//        if ($city_id) {
//            $models = $models->where('city_id', $city_id);
//        }
        $put_house = $models->where('status', 1)->orderBy('sort', 'asc')->orderBy('id', 'desc')->get();
        foreach ($put_house as $value) {
            if ($value['drawing']) {
                $value['drawing'] = getAliOssImage($value['drawing']);
            }
            if ($value['project']) {
                $value['project'] = getAliOssImage($value['project']);
            }
        }
        $array['put_house'] = $put_house;
        //活动
        $article = Article::where('class_id', 2)->orderBy('id', 'desc')->limit(4)->get();
        foreach ($article as $value) {
            if ($value['thumb']) {
                $value['thumb'] = getAliOssImage($value['thumb']);
            }
        }
        $array['article'] = $article;
        return showMsg('获取成功', 200, $array);
    }

    //获取图片验证码
    public function getImageCode()
    {
        $captcha_expire = 180;
        $captchaParams = app('captcha')->create('mini', true);
        $captcha_key = $captchaParams['key'];
        // 缓存起来
        Cache::put("captcha:" . md5($captcha_key), 1, $captcha_expire);
        return showMsg('获取成功', 200, $captchaParams);
    }

    //获取手机验证码
    public function getMobileCode(Request $request)
    {
        $data = $request->all();
        if (!Cache::get("captcha:" . md5($data['key']))) {
            return showMsg('验证码已过期，请刷新重试', 201);
        }
        if (!captcha_api_check($data['code'], $data['key'])) {
            return showMsg('图片验证码不正确', 201);
        }
        if (!Cache::get("captcha:" . md5($data['key']))) {
            return showMsg('验证码已过期，请刷新重试', 201);
        }
        if (empty($data['mobile']) || !is_mobile($data['mobile'])) {
            return showMsg('手机格式不正确', 201);
        }
        if (Smsrecord::wherePhone($request->mobile)->whereBetween('created_at', [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')])->count() > 8) {
            return showMsg('短信发送太频繁 ', 201);
        }
        //判断来源
        $from = $request->get('type');
        if ($from == 1) { //注册发送验证码
            if (YtkUsers::whereMobile($request->mobile)->first()) {//已注册
                return showMsg('手机号已注册', 201);
            }
        }
//        if ($data['mobile'] == '18736099307' || $data['mobile'] == '19937374476') {
//            return showMsg('发送成功', 200);
//        }
        $easySms = new EasySms(config('sms'));
        $code = rand(1000, 9999);
        try {
            $r = $easySms->send($data['mobile'],
                [
                    'content' => "【益题库】您的验证码是" . $code . "。如非本人操作，请忽略本短信",
                ], ['yunpian']);
        } catch (Exception $e) {
            $title = $e->getLastException();
            return showMsg($title->raw['msg'], 201);
        }
        if ($r['yunpian']['status'] == 'success') {
            //存储
            $arr = [
                'phone' => $data['mobile'],
                'code' => $code
            ];
            Smsrecord::insert($arr);
            return showMsg('发送成功', 200);
        }
        return showMsg('发送失败');
    }

    //获取手机验证码
    public function sendmsg(Request $request)
    {
        $data = $request->all();
        $imgKeys = $request->get('imgKeys');
        $code = $data['code'];
        if ($imgKeys) {
            if (!captcha_api_check($code, $imgKeys)) {
                return showMsg('图片验证码不正确', 201);
            }
        }

        if (empty($data['phone']) || !is_mobile($data['phone'])) {
            return showMsg('手机格式不正确', 201);
        } else {
            if ($data['phone'] == '18736099307') {
                return showMsg('发送成功', 200);
            }
        }
        if (Smsrecord::wherePhone($request->phone)->whereBetween('created_at', [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')])->count() > 5) {
            return showMsg('短信发送太频繁 ', 201);
        }
        $easySms = new EasySms(config('sms'));
        $code = rand(1000, 9999);
        try {
            $r = $easySms->send($data['phone'],
                [
                    'content' => "【益题库】您的验证码是" . $code . "。如非本人操作，请忽略本短信",
                ], ['yunpian']);
        } catch (Exception $e) {
            $title = $e->getLastException();
            return showMsg($title->raw['msg'], 201);
        }
        if ($r['yunpian']['status'] == 'success') {
            //存储
            $arr = [
                'phone' => $data['phone'],
                'code' => $code
            ];
            Smsrecord::insert($arr);
            return showMsg('发送成功', 200);
        }
        return showMsg('发送失败');
    }

    //我的二维码
    public function getUnlimited(Request $request)
    {
        $app = app('wechat.mini_program');
        $result = $app->app_code->getUnlimit($this->uId, [
            'page' => 'pages/index/index',
            'width' => 600,
        ]);
        return showMsg('获取成功', 200, $result);
    }

    //我的协议
    public function getAgreement(Request $request)
    {
        $re = YtkConfig::find(1);
        return showMsg('获取成功', 200, $re);
    }

    //上传文件并返回文件path和url
    public function upload(Request $request)
    {
        //上传文件最大大小,单位M
        $maxSize = 10;
        //支持的上传图片类型
        $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
        //返回信息json
        $data = ['status' => 201, 'msg' => '上传失败', 'data' => ''];
        $file = $request->file('image');
        //检查文件是否上传完成
        if ($file->isValid()) {
            //检测图片类型
            $ext = $file->getClientOriginalExtension();
            if (!in_array(strtolower($ext), $allowed_extensions)) {
                $data['msg'] = "请上传" . implode(",", $allowed_extensions) . "格式的图片";
                return response()->json($data);
            }
            //检测图片大小
            if ($file->getClientSize() > $maxSize * 1024 * 1024) {
                $data['msg'] = "图片大小限制" . $maxSize . "M";
                return response()->json($data);
            }
        } else {
            $data['msg'] = $file->getErrorMessage();
            return response()->json($data);
        }

        if (empty($file)) {
            $return = [
                'status' => 201,
                'msg' => '请选择图片上传'
            ];
        } else {
            $path = date('Y-m-d');
            $public = $request->file('image')->store($path, 'article');
            if ($public) {
                $res = Storage::put($public, Storage::disk('article')->get($public));
                if ($res) {
                    $return = [
                        'status' => 200,
                        'filename' => $public,
                        'msg' => Storage::disk('article')->url($public),
                    ];
                } else {
                    $return = [
                        'status' => 200,
                        'filename' => $public,
                        'msg' => Storage::disk('article')->url($public)
                    ];
                }
            } else {
                $return = [
                    'status_code' => 201,
                    'msg' => trans('上传失败')
                ];
            }
        }
        return $return;
    }

}
